//
//
//  AppDelegate.m
//  HengHuaSupervision
//
//  Created by XD-XY on 3/20/14.
//  Copyright (c) 2014 XD-XY. All rights reserved.
//

#import "AppDelegate.h"
#import "MainViewController.h"
#import "LoginViewController.h"
#import "XDTools.h"
#import "Request.h"
@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    
    theLocation = [CLLocationManager new];
    theLocation.delegate = self;
    theLocation.distanceFilter = 100;
    [theLocation startUpdatingLocation];
    [self locationTip];
    
    NSString *udid = [XDTools readPassWord];
    if (udid==nil||udid.length == 0){
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isFirstStart"];
        [[UIApplication sharedApplication] setStatusBarHidden:YES];
        LoginViewController * loginVC = [[LoginViewController alloc] init];
        self.window.rootViewController = loginVC;
    }
    else{
        NSDictionary * dict = [[NSUserDefaults standardUserDefaults] valueForKey:@"USERINFOS"];
        
        if(dict == nil||[dict.allValues count]==0){
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isFirstStart"];
        }else{
            [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isFirstStart"];
        }


        if ([[UserInfo sharedUserInfo].isLogIn intValue] != 1) {
            //[self Login]; ----old
            
            //new
            LoginViewController * loginVC = [[LoginViewController alloc] init];
            self.window.rootViewController = loginVC;
            
        }else{
            [self reSetRootView];
        }
        //end
        
        [[UIApplication sharedApplication] setStatusBarHidden:NO];
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
        

    }
    
    //拷贝数据库到沙盒目录
    [XDTools moveToDBFile];
    
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)reSetRootView{
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    MainViewController * mainVC = [[MainViewController alloc] init];
    UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:mainVC];
    self.window.rootViewController = nav;
}
#pragma mark =====================登录=========================
-(void)Login
{
    
    NSString *udid = [XDTools readPassWord];
    Request * loginRequest = [[Request alloc] init];
    NSString *jsonStr = [NSString stringWithFormat:@"{\"udid\":%@}",udid];
    NSDictionary* requestEntity = [jsonStr objectFromJSONString];
    [XDTools showProgress:self.window];
    [loginRequest request:mTrace_LoginUrl keyValue:requestEntity completionHandler:^(ResponseData *data) {
        [XDTools hideProgress:self.window];
        if([data.result intValue]==1){
            NSDictionary * dic = [XDTools JSonFromString:data.responseJson];
            
            [[UserInfo sharedUserInfo] setValueWithDictionary:[dic valueForKey:@"content"]];
            [XDTools savePassWord:[UserInfo sharedUserInfo].udid];

            MainViewController * mainVC = [[MainViewController alloc] init];
            UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:mainVC];
            self.window.rootViewController = nav;
        }else{
            [XDTools showTips:data.errorMsg toView:self.window];
            DDLOG(@"%@",data.errorMsg);
        }
    }];
    //   [[XDTools appDelegate] reSetRootView];
    DDLOG_CURRENT_METHOD;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark - CLLocation

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation * currentLocation = [locations lastObject];
    CLLocationCoordinate2D coor = currentLocation.coordinate;
    if (![XDTools isValidCoordinate:coor]){
        return;
    }
    
    //latitude和lontitude均为NSString型变量
    //纬度
    NSString * latitude = [NSString  stringWithFormat:@"%.6f", coor.latitude];
    //经度
    NSString * longitude = [NSString stringWithFormat:@"%.6f",coor.longitude];
    
    [[NSUserDefaults standardUserDefaults] setValue:[NSString stringWithFormat:@"(%@,%@)",latitude,longitude] forKey:@"location_gps"];
    
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];

    [geocoder reverseGeocodeLocation: currentLocation completionHandler:^(NSArray *array, NSError *error) {

        if (array.count > 0) {

            CLPlacemark * vplacemark = [array objectAtIndex:0];
            NSString * sttr = [[vplacemark.addressDictionary objectForKey:@"FormattedAddressLines"] objectAtIndex:0];
            [[NSUserDefaults standardUserDefaults] setValue:sttr forKey:@"location"];
        }
    }];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    DDLOG(@"XDAppDelegate:%@",@"localtion fail");
}

- (void)locationTip
{
    if (!([CLLocationManager locationServicesEnabled] && [CLLocationManager authorizationStatus] != kCLAuthorizationStatusDenied)) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"定位服务不可用"
                                                        message:@"建议开启定位服务(设置>定位服务>开启乐度定位服务)"
                                                       delegate:nil
                                              cancelButtonTitle:@"确认"
                                              otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
}

@end
